package com.myk.game.connect6tool.dialogs;

import android.app.Activity;
import android.app.Dialog;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

/**
 * 动态询问用户的意见后再执行后面的流程
 * 这是一个模态阻塞对话框（阻塞主线程，结果不用回调来处理）
 */
public class BlockingChoiceDialog extends Dialog {


    boolean dialogResult;
    Handler mHandler;
    Activity context;
    String question;

    public BlockingChoiceDialog(Activity context, String question) {
        super(context);
        setOwnerActivity(context);
        this.context = context;
        this.question = question;
        onCreate();
    }

    public boolean getDialogResult() {
        return dialogResult;
    }

    public void setDialogResult(boolean dialogResult) {
        this.dialogResult = dialogResult;
    }

    /**
     * Called when the activity is first created.
     */

    public void onCreate() {
        LinearLayout contentView = new LinearLayout(context);
        contentView.setOrientation(LinearLayout.HORIZONTAL);
        setContentView(contentView);
        TextView title = new TextView(context);
        title.setText(question);
        Button yesButton = new Button(context);
        yesButton.setText("YES");
        yesButton.setOnClickListener(v -> endDialog(true));
        Button noButton = new Button(context);
        noButton.setText("NO");
        noButton.setOnClickListener(v -> endDialog(false));
        contentView.addView(title);
        contentView.addView(yesButton);
        contentView.addView(noButton);
    }

    public void endDialog(boolean result) {
        dismiss();
        setDialogResult(result);
        Message m = mHandler.obtainMessage();
        mHandler.sendMessage(m);
    }

    public boolean showDialog() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message mesg) {
                // process incoming messages here
                //super.handleMessage(msg);
                throw new RuntimeException();
            }
        };
        super.show();
        try {
            Looper.getMainLooper().loop();
        } catch (RuntimeException e2) {
        }
        return dialogResult;
    }

}